<?php

namespace Api\Controller;

use Think\Controller;
use Api\Terrace\Helper\WxComponentHelper;
use Think\Cache;
use Api\Util\Helper;
use Api\Util\Aes;
use Api\Terrace\Helper\WebOathHelper;
use Api\Terrace\Helper\WxMessageHelper;

class TerraceController extends Controller
{

    /**
     * 第三方平台事件通知
     */
    public function sysmessage(){
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $wxComponentService->onComponentEventNotify();
    }


    /**
     * 第三方平台发起公众号授权
     */
    public function componentAuth(){
        $config = C('wx_component');
        $type =  isset($_GET['type']) ? $_GET['type'] : die("TYPE MUST EXIST!");
        $id = isset($_GET['id']) ? $_GET['id'] : "";
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        switch($type){
            case "testing"://测评
                if($id){
                    $redirectUrl = $config['callback_url']."?type=".$type."&id=".$id;
                }else{
                    $redirectUrl = $config['callback_url']."?type=".$type;
                }
                break;

        }
        $auth_cb_url = $wxComponentService->getAuthorizeUrl($redirectUrl);
        Helper::log('=======>$auth_cb_url ','Wx_ticket');
        Helper::log($auth_cb_url,'Wx_ticket');
        Helper::log('<======$auth_cb_url ','Wx_ticket');
        $this->assign('auth_cb_url',$auth_cb_url);
        $this->display();
        // return view('WxComponent.auth')->with('auth_cb_url',$auth_cb_url);
    }

    /**
     * 微信第三方平台授权回调页面
     *
     */
    public function callback(){
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $type =  $_GET['type'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $ret = $wxComponentService->authorizeCallbackProcess($_GET['auth_code'], $_GET['expires_in']);
        $id = isset($_GET['id']) ? $_GET['id'] : "";
        if ($ret['code'] === 0) {
            echo "authoriza success!<br>";
            /*switch($type){
                case "testing":
                    if($id){
                        echo "http://tt.qiezilife.com/quesdetail/try/".$id."/0?appid=".base64_encode($ret['appAcountInfo']['authorization_info']['authorizer_appid']);
                    }else{
                        echo "http://tt.qiezilife.com/quesdetail/try/wg9MwrVmqk/0?appid=".base64_encode($ret['appAcountInfo']['authorization_info']['authorizer_appid']);
                    }
                    break;
                case "circle":
                    echo "http://qatest.qiezilife.com/m/circle_detail_list/id-3__show_event-2__appid-".base64_encode($ret['appAcountInfo']['authorization_info']['authorizer_appid']);
                    break;
            }*/
            //echo "appAcountInfo:" . print_r($ret['appAcountInfo'], true);
            //http://tt.qiezilife.com/queslist/0?appid=d3gxNTFjODE4ODVlZmJiY2Q3  全部测评
        } else {
            echo "authoriza error!<br>";
            echo "原因:" . $ret['msg'];
        }
    }

    /**
     * 获取授权公众号基本信息
     */
    public function authorizerInfo(){
        $appid = base64_decode($_GET['appid']);
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $info = $wxComponentService->get_authorizer_info($appid);
        echo json_encode($info);
    }


    /**
     * 代理处理公众号实现业务操作
     */
    public function appEvent(){
        $weObj = $this->weObj();
        $ret = $weObj->valid(true);
        $weObj->getRev();
        $weObj->text("success")->reply('', true); // 简单测试回复success
    }

    /**
     * 第三方平台代公众号发起网页授权一（通过回调实现）
     */
    public function compontneWebAuth(){
        Helper::log('compontneWebAuth ======>');
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $uid_rtn_platforms =C('uid_rtn_platforms');
        $type = $_GET['type'];
        $platform = $_GET['platform'];
        $callbackUrl = $_GET['callbackUrl'];
        $code = $_GET['code'];
        $scope = $_GET['scope'];
        $appid = $_GET['appid'];
        if(!$scope) $scope = 'snsapi_base';
        $webOath = new WebOathHelper();
        $ComponentAccessTocken = $wxComponentService->getComponentAccessTocken();
        //获取用户信息之后
        $user = $webOath->webAuthorize($callbackUrl,$platform,$type,$code,$scope,$appid,$ComponentAccessTocken);
        $uid = $user['uid'];
        $salt = $user['salt'];
        $expire = time()+C('COOKIE_EXPIRE');
        $login_key="login_key_".$appid;

        Helper::log('login_key=======> '.$login_key);

        cookie($login_key,null);
        $auth_key =  Helper::get_auth_cookie($user['openid'], $uid, $salt, $expire);
        $expire = C('COOKIE_EXPIRE');
        cookie($login_key, $auth_key, $expire, '/', 'qiezilife.com');
        $redis_key = C('REDIS_PREFIX').C('REDIS_USER_PREFIX').$uid;

        Helper::log('after user info=======> '.$user);
//        $cacheUser = $cache->$redis_key;
        //判断是否需要重新更新缓存，所有的其他的业务系统信息都是从缓存中读取
//        Helper::log('$cacheUser=======> '.json_encode($cacheUser));
//        if(!$cache->exists($redis_key)){
//            Helper::log('login_key=======> '.$login_key);
            $cache->set($redis_key,json_encode($user));
//        }
        $callbackUrl = base64_decode($callbackUrl);
        //由于使用laravel框架用户信息无法从cookie中获取
        if(in_array($platform,$uid_rtn_platforms) ){
            $str = $user['openid'].'|'.$uid.'|'.$salt.'|'.$expire;
            $user_auth_key = urlencode(base64_encode($str));
            cookie('cookie_key',null);
            $other_key = 'cookie_key';
            $auth = C('SECRET_KEY');
            $user_auth_key = Aes::encode($auth,$user_auth_key);
            cookie('cookie_key', $user_auth_key, $expire, '/', 'qiezilife.com');
            if(in_array($platform,$uid_rtn_platforms)){
                $callbackUrl = $callbackUrl.'/'.$uid.'/'.base64_encode($appid);
            }
        }
        Helper::log('callbackUrl ======>'.$callbackUrl);
        header('Location: '.$callbackUrl);
        die(0);
    }

    /**
     * 第三方平台代公众号发起网页授权二（通过直接调用实现，需提交appid）
     */
    public function webOauth(){
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        if(isset($_GET['code']) && $_GET['state'] == 'fromqiezioauth' && isset($_GET['appid'])){//已进入授权页面
            $ret = $wxComponentService->getOauthAccessTokenForCode($_GET['appid']);
            if($ret){
                $user = $wxComponentService->getOauthUserinfo($ret['access_token'],$ret['openid']);
                print_r($user);
            }
            exit;
        }else{//跳转接口授权
            $appId = $_GET['appid'];
            $redirectUrl = $config['oauth_url'];
            $oauth_url = $wxComponentService->getOauthRedirect($appId,$redirectUrl,"fromqiezioauth","snsapi_userinfo");
            $this->assign('oauth_url',$oauth_url);
            $this->display();
            //return view('WxComponent.wxAuth')->with('oauth_url',$oauth_url);
        }

    }

    /*
     *微信jssdk
     */
    public function jsSdk(){
        $appId =  base64_decode($_GET['appid']);
        $url = $_GET['url'];
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $signPackage = $wxComponentService->getJsSign($appId, $url);
        echo  json_encode($signPackage);
    }

    /**微信消息接收
     * @param $appid 授权公众号id
     */
    public function eventmsg(){
        $appId = $_GET['appid'];
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $wxMessage = new WxMessageHelper($wxComponentService,$appId,$cache);
        //全网发布时，验证消息接口，更改为自动化测试方法
        //$this->test_auto_case($wxComponentService,$appId);
        $wxMessage->response_message();

    }


    /**带参二维码
     * @param $appid 授权公众号id
     * @param $scene_id 场景id
     */
    public function qrcode(){
        $appId = base64_decode($_GET['appid']);
        $scene_id = $_GET['scene_id'];
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $weObj = $wxComponentService->getWechat($appId);
        $ticket = $weObj->getQRCode($scene_id);
        $qecodeurl = $weObj->getQRUrl($ticket['ticket']);
        header('Location: '.$qecodeurl);
    }

    /**发送模板消息
     * @param $appid 授权公众号id
     * @param $scene_id 场景id
     *  {package:cewfergergegeg}
     */
    public function sendTemplate(){
        $appId = base64_decode($_GET['appid']);
        $template_id = $_GET['tplid'];
        $json=file_get_contents("php://input");
        $package = json_decode($json,true);
        //解密消息模板
        $tpl = base64_decode($package['package']);
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this -> cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig,$cache);
        $wxMessage = new WxMessageHelper($wxComponentService,$appId,$cache);
        $wxMessage->sendTplMsg($template_id,$tpl,$appId);
    }



    /**授权后的公众号对象
     * @return \App\Terrace\Depend\Wechat\Wechat
     */
    protected function weObj()
    {
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];//当前url
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $cache = $this->cacheObj();
        $wxComponentService = new WxComponentHelper($wxComponentConfig, $cache);
        $cfg = $wxComponentService->get_wx_config();
        $appId = $cfg['app_id'];
        if ($appId == 'wx151c81885efbbcd7') {
            // 如果为全网发布接入检测的专用测试公众号，转入自动化测试代码
            $this->test_auto_case($wxComponentService, $appId);
            exit;
        }

        // 检验公众号是否授权
        if (!$wxComponentService->isValidAuthorizedAppId($appId)) {
            Helper::log('=======>isValidAuthorizedAppId', 'Wx_ticket');
            Helper::log("appId:{$appId}, not valid authroized appId param:" . print_r($_GET, true), 'Wx_ticket');
            Helper::log('<======isValidAuthorizedAppId', 'Wx_ticket');
            die('no access');
        }
        //授权后的公众号对象，代理处理公众号实现业务操作
        $weObj = $wxComponentService->getWechat($appId);
        if (!$weObj) {
            Helper::log('=======>weObj', 'Wx_ticket');
            Helper::log("appId:{$appId}, not valid authroized appId param:" . print_r($_GET, true), 'Wx_ticket');
            Helper::log('<======weObj', 'Wx_ticket');
            die('no access');
        }

        return $weObj;
    }


    /**自动化测试代码
     * @param $wxComponentService
     * @param $appId
     */
    protected function test_auto_case(&$wxComponentService, $appId){
        if (!$wxComponentService->isValidAuthorizedAppId($appId)) { // 判断公众号授权是否有效
            Helper::log('=======>testAppId','Wx_ticket');
            Helper::log( "appId:{$appId}, not valid authroized appId param:" . print_r($_GET, true),'Wx_ticket');
            Helper::log('<======testAppId','Wx_ticket');
            die('no access');
        }
        $weObj = $wxComponentService->getWechat($appId);
        if (!$weObj) {
            Helper::log('=======>testweObj','Wx_ticket');
            Helper::log( "appId:{$appId}, not valid authroized appId param:" . print_r($_GET, true),'Wx_ticket');
            Helper::log('<======testweObj','Wx_ticket');
            die('no access');
        }
        $ret = $weObj->valid(true);
        if ($ret === false) {
            die('no access');
        } else if ($ret !== true) {
            die($ret);
        }
        $weObj->getRev();
        if ($weObj->getRevType() == $weObj::MSGTYPE_TEXT) {
            $recv_txt = $weObj->getRevContent();
            if ($recv_txt == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
                $weObj->text('TESTCOMPONENT_MSG_TYPE_TEXT_callback')->reply('', false);
                exit;
            } else if (preg_match('#QUERY_AUTH_CODE:(.*)#', $recv_txt, $matches)) {

                $weObj->text('')->reply('', false);

                $ret = $wxComponentService->authorizeCallbackProcess($matches[1], 10);
                if ($ret['code'] != 0) {
                    exit;
                }
                $weObj->access_token = $wxComponentService->getAppAccessToken($ret['appAcountInfo']['authorization_info']['authorizer_appid']);
                $res_arr = array('touser' => $weObj->getRevFrom(), 'msgtype' => 'text', 'text' => array('content' => $matches[1] . "_from_api"));
                $ret = $weObj->sendCustomMessage($res_arr);
                if (!$ret) {
                }
                exit;
            }
        } else if ($weObj->getRevType() == $weObj::MSGTYPE_EVENT) {
            $data = $weObj->getRevData();
            $ev = $data['Event'];
            $weObj->text($ev . "from_callback")->reply('', false);
        } else {
            die("no access");
        }
        exit;
    }

    /**返回缓存对象
     * @return mixed
     */
    protected function cacheObj(){
        $redis_info = C('REDIS');
        $cacheObj = Cache::getInstance('Redis', $redis_info);
        return $cacheObj;
    }


//http://localhost/testing-server/server.php/terrace/callback?component_appid=wx083e534bbdb1b02e&auth_code=queryauthcode@@@m5sxMXfzP8lgdJLxnhV6sEXlkY6sZ-ZQ68RGfAvEOs_6Z-yMoRRnywM9eTAjhquFhptg7DGs0X3lcF0L61-XaA&expires_in=3600
}
